package main.java.modules.weixin.controller;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.common.utils.StringUtils;

import main.java.common.model.Product;
import main.java.common.util.AddressUtils;
import main.java.common.util.DateUtil;
import main.java.modules.weixin.service.WeiXinPayService;
import main.java.modules.weixin.util.ConfigUtil;
import main.java.modules.weixin.util.HttpUtil;
import main.java.modules.weixin.util.PayCommonUtil;
import main.java.modules.weixin.util.XMLUtil;
import main.java.modules.weixin.util.mobile.MobileUtils;
/**
 * 微信h5支付
 * @author D
 *
 */
@Controller
@RequestMapping("/weixinMobile")
public class WeixinPayMobileController {
	private static final Logger logger = LoggerFactory.getLogger(WeixinPayMobileController.class);
	
	@Autowired
	private WeiXinPayService weixinPayService;
	
	@Value("${server.context.util}")
	private String server_url;
	
	@RequestMapping("/pay")
	public String pay(Product product,ModelMap map) {
		logger.info("H5支付(需要公众号内支付)");
		String url = weixinPayService.weixinPayMobile(product);
		return "redirect:" + url;
	}
	@RequestMapping("/h5pay")
	public String h5pay(Product product, ModelMap map) {
		logger.info("纯h5支付  不建议在app端使用");
		//web_url 为调用微信支付收银台的中间页面，可以访问该url来弹出微信支付客户端
		String web_url = weixinPayService.weixinPayH5(product);
		if(!StringUtils.isBlank(web_url)) {
			return "redirect:" + web_url;
		} else {
			//自定义错误页面
			return "redirect:https://" ;
		}
	}
	
	/**
	 * 预下单 对于已经产生的订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/dopay")
	public String dopay(HttpServletRequest request, HttpServletResponse response) {
		String state = request.getParameter("state");
		String[] split = state.split("/");
		String orderNo = split[0];
		String totalFee = split[1];
		//微信支付调用会自动加上code参数 无需设置
		String code = request.getParameter("code");
		String openId = MobileUtils.getOpenId(code);
		//回调接口
		String notify_url = server_url + "/weixinMobile/WXPayBack";
		//交易类型H5支付
		String trade_type = "JSAPI";
		SortedMap<Object, Object> pakageParams= new TreeMap<Object, Object>();
		ConfigUtil.commonParams(pakageParams);
		pakageParams.put("body", "报告");
		pakageParams.put("out_trade_no", orderNo);
		pakageParams.put("total_fee", totalFee);
		//发起人ip
		pakageParams.put("spblill_create_ip", AddressUtils.getIpAddr(request));
		pakageParams.put("notify_url", notify_url);
		pakageParams.put("trade_type", trade_type);
		pakageParams.put("openid", openId);
		String sign = PayCommonUtil.createSign("UTF-8",pakageParams,ConfigUtil.API_KEY);
		//签名
		pakageParams.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXML(pakageParams);
		String resXML = HttpUtil.postData(ConfigUtil.UNIFIED_ORDER_URL, requestXML);
		Map map = XMLUtil.doXMLParse(resXML);
		String returnCode = (String)map.get("return_code");
		String returnMsg = (String)map.get("return_msg");
		StringBuffer url = new StringBuffer();
		if("SUCCESS".equals(returnCode)) {
			String resultCode = (String)map.get("reult_code");
			String errCodeDes = (String)map.get("err_code_des");
			if("SUCCESS".equals(resultCode)) {
				//获取预支付交易会话标识
				String prepay_id = (String)map.get("prepay_id");
				String prepay_id2 = "prepay_id=" + prepay_id;
				String packages = prepay_id;
				SortedMap<Object, Object> finalpackage = new TreeMap<Object,Object>();
				String timestamp = DateUtil.getTimestamp();
				String nonceStr = pakageParams.get("nonce_str").toString();
				finalpackage.put("appId", ConfigUtil.APP_ID);
				finalpackage.put("timeStamp", timestamp);
				finalpackage.put("nonceStr", nonceStr);
				finalpackage.put("signType", "MD5");
				sign = PayCommonUtil.createSign("UTF-8", finalpackage, ConfigUtil.API_KEY);
				url.append("redirect:/weixinMobile/pay?");
				url.append("timeStamp="+timestamp+"&nonceStr=" + nonceStr + "&package=" + packages);
				url.append("&signType=MD5" + "&paySign=" + sign+"&appid="+ ConfigUtil.APP_ID);
				url.append("&orderNo="+orderNo+"&totalFee="+totalFee);
			} else {
				logger.info("订单号:{}错误信息:{}",orderNo,errCodeDes);
				url.append("redirect:/weixinMobile/error?code=0&orderNo="+orderNo);//该订单已支付
			}
		} else {
			logger.info("订单号:{}错误信息:{}",orderNo,returnMsg);
			url.append("redirect:/weixinMobile/error?code=1&orderNo="+orderNo);//系统错误
		}
		return url.toString();
	}
	
	
}
